/* eslint-disable react/prop-types */
/**
 * Created by jianyijun on 2020/03/20.
 * 欢迎启动页面
 */
import React, { Component } from 'react';
import {
  StatusBar,
  View,
  Image,
  StyleSheet,
  Text,
  NativeModules,
  DeviceEventEmitter,
  Dimensions,
  Alert,
  Linking
} from 'react-native';
import SplashScreen from 'react-native-splash-screen';
import { StackActions, NavigationActions } from 'react-navigation';
import getStorageValue from './utils/getStorageValue';
import fetchWebApi from './public/WebApi/fetchBase';
import { VERSION_CHECK } from './public/WebApi/apiList';
import { Constant } from './public/js/constant';
import packageInfo from '../package.json';
import { Actions } from 'react-native-router-flux'

import moment from 'moment';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
const downloadData = [];

export default class StartPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      updata: false,
      progress: '0',
      searchModel: {
        ICode: '',
        QueryStartDate: moment()
          .add(-3, 'M')
          .format('YYYY-MM-DD'),
        QueryEndDate: moment().format('YYYY-MM-DD'),
        QueryWords: '',
      },
    };
  }

  UNSAFE_componentWillMount() {
    this.timer = setTimeout(() => {
      // app 版本检测
      this.goPage();
      // this.props.navigation.dispatch('homePage');
      // Actions.replace('MedicalWorkers')

      // 隐藏欢迎页
      SplashScreen.hide();
      // this.props.navigation.push('Accountlogin')
    }, 1500);
  }

  componentDidMount() {
  }

  async goPage() {
    let resetActiom;
    const token = await getStorageValue(Constant.TOKEN);
    let routeName = "Accountlogin";
    if (token) {
      //Accountlogin Verificationcodelogin
      routeName = "maillist";
      Actions.maillist()
    } else {
      //MainStack
      routeName = "Accountlogin";
      Actions.replace('Accountlogin');
    }
    // 重构路由页面, 无法返回欢迎页面
    // 这里有几个就保留几个，点击完成后就会重构导航器
    // resetActiom = StackActions.reset({
    //   index: 0, // 默认打开actions中的第几个页面
    //   actions: [
    //     NavigationActions.navigate({ routeName: routeName }),
    //   ],
    // });
    // this.props.navigation.dispatch(resetActiom);
  }

  async checkVersion() {
    const res = await fetchWebApi(VERSION_CHECK, { versionCode: parseInt(packageInfo.versioncode) }, 'POST');
    console.log("####### checkVersion")
    console.log(res)

    //  版本服务异常
    if (res.status != 200) {
      return this.goPage();
    }

    let newVersion = res.data[0];
    // console.log("newVersion");
    // console.log(newVersion);
    // 当前已是最新版本，无需更新
    if (newVersion === undefined) {
      return this.goPage();
    } else {
      if (newVersion.length == 0) {
        return this.goPage();
      }
    }

    let upgradeFlag = 0;
    if (packageInfo.versioncode < newVersion.versionCode) {
      res.msg = "您当前使用的版本过低，请及时更新";
      upgradeFlag = 1;
    }

    if (upgradeFlag == 1) {
      if (global.__ANDROID__) {
        Alert.alert(
          res.msg + newVersion.verName,
          newVersion.remark + ' 是否下载',
          [
            {
              text: '确定',
              onPress: () => {
                this.setState({ updata: true });
                NativeModules.upgrade.upgrade(newVersion.androidUrl);
              },
            },
            {
              text: '取消',
              onPress: () => {
                this.goPage();
              },
            },
          ],
        );

        DeviceEventEmitter.addListener('LOAD_PROGRESS', msg => {
          if (msg < 100) {
            downloadData.push('1');
          }
          this.setState({
            progress: msg,
          });
          if (msg === 100) {
            this.setState({
              updata: false,
            });
            this.goPage();
          }
        });
      }
      else if (global.__IOS__) {
        Alert.alert(
          res.msg + newVersion.verName,
          newVersion.remark + ' 是否下载',
          [
            {
              text: '确定',
              onPress: () => {
                Linking.openURL(newVersion.iosUrl)
                this.goPage();
              },
            },
            {
              text: '取消',
              onPress: () => {
                this.goPage();
              },
            },
          ],
        );
      }
    }
    else {
      this.goPage();
    }
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <StatusBar hidden={true} />
        <Image
          source={require('./assets/images/splash.png')}
          style={{ height: height, width: width }}
        />
        {this.state.updata ? (
          <View style={styles.updataRootView}>
            <View style={styles.updataView1}>
              <Text style={styles.updataView1Text1}>正在下载中...</Text>
              <View style={styles.updataView2}>
                {downloadData.map((item, i) => {
                  return <View key={i} style={styles.updataMapView} />;
                })}
              </View>
              <Text style={styles.updataMapViewText}>{`已下载：${this.state.progress
                }%`}</Text>
            </View>
          </View>
        ) : null}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  // app升级 下载
  updataRootView: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: width,
    height: height,
    backgroundColor: 'rgba(0,0,0,.4)',
    alignItems: 'center',
  },
  updataView1: {
    height: 120,
    width: 260,
    backgroundColor: '#fff',
    borderRadius: 5,
    marginTop: 0.4 * height,
    alignItems: 'center',
  },
  updataView1Text1: {
    fontSize: 18,
    color: '#000',
    fontWeight: 'bold',
    marginTop: 6,
  },
  updataView2: {
    height: 10,
    width: 200,
    borderWidth: 1,
    borderColor: '#8BC817',
    flexDirection: 'row',
    overflow: 'hidden',
    borderRadius: 10,
    marginTop: 20,
  },
  updataMapView: {
    height: 50,
    width: 2,
    backgroundColor: '#8BC817',
  },
  updataMapViewText: {
    fontSize: 14,
    color: '#8BC817',
    marginTop: 6,
  },
});
